package com.itheima.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.channels.MulticastChannel;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;

@RestController
@RequestMapping("/dfs")
@Slf4j
@Api("文件微服")
public class FileController {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private WmMaterialFeign wmMaterialFeign;

    /**
     * 上传文件
     * @param multipartFile
     * @return 文件的远程路径
     */
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile multipartFile){
        // 获取请求的来源  鉴权
        String from = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if(StringUtils.isEmpty(from)){
            throw new LeadNewsException("拒绝上传");
        }

        //获取上传文件的后缀名
        String ext = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());
        try {
            //上传给fastdfs服务器
            StorePath storePath = client.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), ext, null);

            //远程调用自媒体 添加素材记录
            if(SystemConstants.WEMEDIA_PIC.equals(from)){
                addWmMaterial(storePath);
            }

            /**
             * {url:地址}
             */
            Map<String, String> result = Collections.singletonMap("url", webServer.getWebServerUrl() + storePath.getFullPath());
            return ResultVo.ok(result);
        } catch (IOException e) {
            log.error("上传文件失败",e);
        }
        return ResultVo.bizError("上传文件失败！");
    }

    /**
     * 远程调用自媒体 添加素材
     * @param storePath
     */
    private void addWmMaterial(StorePath storePath) {
        //1. 构建素材对象
        log.info("添加素材");
        //构建pojo
        WmMaterial pojo = new WmMaterial();
        pojo.setUrl(storePath.getFullPath());
        pojo.setIsCollection(0);//0：未收藏
        pojo.setCreatedTime(LocalDateTime.now());
        pojo.setType(0);// 0：图片
        pojo.setUserId(Long.parseLong(RequestContextUtil.getUserId()));
        //2. 远程调用
        ResultVo result = wmMaterialFeign.addWmMaterial(pojo);
        //3. 调用失败要报错
        if(!result.isSuccess()){
            throw new LeadNewsException("文件上传，调用自媒体添加素材失败");
        }
        log.info("添加素材成功");
    }
}
